package com.star.wellconnect.appts;

import java.sql.Time;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.Locale;

import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.text.Editable;
import android.text.TextWatcher;
import android.text.format.DateFormat;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

import com.jeremyfeinstein.slidingmenu.lib.SlidingMenu;
import com.star.wellconnect.BaseActivity;
import com.star.wellconnect.R;
import com.star.wellconnect.sqlite.AppPreferences;
import com.star.wellconnect.sqlite.Appointment;
import com.star.wellconnect.sqlite.Patient;

public class ApptActivity extends BaseActivity {
	private ApptActivity context = this;
	private static final String TIME_PICKER = "timePicker";
	private static final String DATE_PICKER = "datePicker";
	private static EditText mDate;
	private static String dbDate;
	private static String dbTime;
	private static EditText mTime;
	private static EditText mAddress;
	
	public ApptActivity(){
		super(R.string.app_name);
	}
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_appt);
		
		// Get info from database
		final Patient patient = AppPreferences.getPatient(this);
		
		// Get layout elements
		final EditText name = (EditText) findViewById(R.id.name);
		final EditText doctor = (EditText) findViewById(R.id.doctor);
		final EditText notes = (EditText) findViewById(R.id.notes);
		final TextView error = (TextView) findViewById(R.id.error);
		Button save = (Button) findViewById(R.id.save);
		mDate = (EditText) findViewById(R.id.date);
		mTime = (EditText) findViewById(R.id.time);
		mAddress = (EditText) findViewById(R.id.address);
		
		// Listener
		TextWatcher inputFieldsValidatorTextWatcher = new TextWatcher(){
			@Override
			public void afterTextChanged(Editable arg0) {}
			
			@Override
			public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {}
			
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				error.setText("");
			}
		};
		// Set listener
		name.addTextChangedListener(inputFieldsValidatorTextWatcher);
		doctor.addTextChangedListener(inputFieldsValidatorTextWatcher);
		mDate.addTextChangedListener(inputFieldsValidatorTextWatcher);
		mTime.addTextChangedListener(inputFieldsValidatorTextWatcher);
		mAddress.addTextChangedListener(inputFieldsValidatorTextWatcher);
		notes.addTextChangedListener(inputFieldsValidatorTextWatcher);
		
		mDate.setOnFocusChangeListener(new View.OnFocusChangeListener() {
			@Override
			public void onFocusChange(View v, boolean hasFocus) {
				if(hasFocus){
					DialogFragment dialog = new DatePickerFragment();
					dialog.show(getSupportFragmentManager(), DATE_PICKER);
				}
			}
		});
		mTime.setOnFocusChangeListener(new View.OnFocusChangeListener() {
			@Override
			public void onFocusChange(View v, boolean hasFocus) {
				if(hasFocus){
					DialogFragment dialog = new TimePickerFragment();
					dialog.show(getSupportFragmentManager(), TIME_PICKER);
				}
			}
		});
		save.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				if(isNotEmpty()){
					Appointment appt = new Appointment(0, name.getText().toString(), 
							doctor.getText().toString(), dbDate, dbTime, mAddress.getText().toString(), 
							notes.getText().toString());
					long status = AppPreferences.addAppointment(
							getApplicationContext(), appt, patient.username);
					
					if(status >= 0){
						Toast.makeText(getApplicationContext(), 
								getResources().getString(R.string.appt_added), Toast.LENGTH_SHORT).show();
						context.finish();
					}else{
						error.setText(getResources().getString(R.string.error_occured));
					}
				}else{
					error.setText(getResources().getString(R.string.fill_required_field));
				}
			}
			
			private boolean isNotEmpty(){
				return name.getText().toString().trim().length() > 0
				&& doctor.getText().toString().trim().length() > 0
				&& mDate.getText().toString().trim().length() > 0
				&& mTime.getText().toString().trim().length() > 0
				&& mAddress.getText().toString().trim().length() > 0;
			}
		});
		
		getActionBar().setDisplayHomeAsUpEnabled(false);
		getSlidingMenu().setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN);
	}
	
	public static class TimePickerFragment extends DialogFragment 
						implements TimePickerDialog.OnTimeSetListener{
		@Override
	    public Dialog onCreateDialog(Bundle savedInstanceState) {
	        // Use the current time as the default values for the picker
			final Calendar c = Calendar.getInstance();
			int hour = c.get(Calendar.HOUR_OF_DAY);
			int minute = c.get(Calendar.MINUTE);
			
			// Create a new instance of TimePickerDialog and return it
		    return new TimePickerDialog(getActivity(), this, hour, minute,
		            DateFormat.is24HourFormat(getActivity()));
		}
		@Override
		public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
			Time time = new Time(hourOfDay, minute, 0);
			dbTime = new SimpleDateFormat(AppPreferences.MILITARY_TIME, Locale.US).format(time);
			mTime.setText(new SimpleDateFormat(AppPreferences.AM_PM_TIME, Locale.US).format(time));
		}
		
	}
	
	public static class DatePickerFragment extends DialogFragment
	    implements DatePickerDialog.OnDateSetListener {
	
		@Override
		public Dialog onCreateDialog(Bundle savedInstanceState) {
			// Use the current date as the default date in the picker
			final Calendar c = Calendar.getInstance();
			int year = c.get(Calendar.YEAR);
			int month = c.get(Calendar.MONTH);
			int day = c.get(Calendar.DAY_OF_MONTH);
			
			// Create a new instance of DatePickerDialog and return it
			return new DatePickerDialog(getActivity(), this, year, month, day);
		}
		
		public void onDateSet(DatePicker view, int year, int month, int day) {
			GregorianCalendar dt = new GregorianCalendar(year, month, day);
			dbDate = new SimpleDateFormat(
					AppPreferences.SQL_DATE, Locale.US).format(dt.getTime());
			mDate.setText(new SimpleDateFormat(
					AppPreferences.DOW_SMIY_DATE, Locale.US).format(dt.getTime()));
		}
	}
}
